import React, {
  Component
} from 'react';
import PropTypes from 'prop-types';
import ReactNative, {
  EdgeInsetsPropType,
  Image,
  NativeMethodsMixin,
  Platform,
  requireNativeComponent,
  StyleSheet,
  View,
  UIManager,
  ViewPropTypes,
} from 'react-native';

export default class ScanCodeView extends Component {

  static defaultProps = {
    scanSize: {
      height: 300,
      width: 300
    },
    autoStartRunning: true,
  };  // 注

  static propTypes = {
    ...ViewPropTypes,

    style: ViewPropTypes.style,
    contentInset: EdgeInsetsPropType,
    /**
     * 是否进入时自动开启扫描
     */
    autoStartRunning: PropTypes.bool,
    /**
     * 设置描框的背景颜色
     */
    maskViewBackgroundColor: PropTypes.string,
    /**
     * 设置边框的颜色
     */
    maskViewBorderColorColor: PropTypes.string,
    /**
     * 读取到Code 后回调
     */
    onCodeRead: PropTypes.func.isRequired,
    /**
     * 出错时调用的接口
     */
    onErrorMessage: PropTypes.func,

    scanSize: PropTypes.shape({
      /*
       * 扫描框的高
       */
      height: PropTypes.number.isRequired,
      /*
       * 扫描框的宽
       */
      width: PropTypes.number.isRequired
    }),
  }

  constructor(props) {
    super(props);
    this.currentCodeRead = this._onCodeRead.bind(this);
    this.currentErrorMessage = this._onErrorMessage.bind(this);
  }

  _onCodeRead(event: Event) {
    var onCodeRead = this.props.onCodeRead;
    if (onCodeRead) {
      onCodeRead(event);
    }
  }

  _onErrorMessage(event: Event) {
    var proError = this.props.onErrorMessage;
    if (proError) {
      proError(event.nativeEvent);
    }
  }

  componentDidMount() {
  }

  //组件移除
  componentWillUnmount() {
    // this.flashClose();
    this.closeScan();
  }

  /**
   * 打开扫描
   */
  openScan() {
    UIManager.dispatchViewManagerCommand(
      this.getViewHandle(),
      UIManager.ScanCodeView.Commands.start,
      []
    );
  }

  /**
   * 关闭当前照像机
   */
  closeScan() {
    UIManager.dispatchViewManagerCommand(
      this.getViewHandle(),
      UIManager.ScanCodeView.Commands.stop,
      []
    );
  }

  /**
   * 打开闪光灯
   */
  flashOpen() {
    UIManager.dispatchViewManagerCommand(
      this.getViewHandle(),
      UIManager.ScanCodeView.Commands.flashOpen,
      []
    );
  }

  /**
   * 关闭闪光灯
   */
  flashClose() {
    UIManager.dispatchViewManagerCommand(
      this.getViewHandle(),
      UIManager.ScanCodeView.Commands.flashClose,
      []
    );
  }

  /**
   * 重新扫描
   */
  restart() {
    UIManager.dispatchViewManagerCommand(
      this.getViewHandle(),
      UIManager.ScanCodeView.Commands.restart,
      []
    );
  }

  getViewHandle() {
    return ReactNative.findNodeHandle(this.refs["ScanCodeNative"]);
  }

  render() {
    return <ScanCodeNative {...this.props}
                           ref="ScanCodeNative"
                           onCodeRead={this.currentCodeRead}
                           onErrorMessage={this.currentErrorMessage}/>;
  }
}

var ScanCodeNative = requireNativeComponent('ScanCodeView', ScanCodeView);
